//
//  AppSetting.m
//  Finder
//
//  Created by cdm on 11-4-1.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "AppSetting.h"


@interface AppSetting()

@property (nonatomic, retain) NSString *plistPath; 

- (NSString *)plistPathInDocumentWithName:(NSString *)name;
- (NSString *)plistPathInAppWithName:(NSString *)name;

@end

@implementation AppSetting

@synthesize background;
@synthesize registered;
@synthesize plistPath;

- (void)dealloc
{
    [self.background release];
    [self.plistPath release];
    [super dealloc];
}

+ (AppSetting *)settingFromPlist:(NSString *)name
{
    AppSetting *setting = [[[AppSetting alloc] init] autorelease];
    [setting initFromPlist:name];
    return setting;
}

- (void)initFromPlist:(NSString *)name
{
    NSString *plistPathInDocument = [self plistPathInDocumentWithName:name];
    NSString *plistPathInApp = [self plistPathInAppWithName:name];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:plistPathInDocument]) {
        [fileManager copyItemAtPath:plistPathInApp toPath:plistPathInDocument error:nil];
    } 
 
    self.plistPath = plistPathInDocument;
    NSDictionary *appSettingDict = [NSDictionary dictionaryWithContentsOfFile:self.plistPath];
    
    self.background = [appSettingDict objectForKey:@"background"];
    self.registered = [[appSettingDict objectForKey:@"registered"] boolValue];
}

- (void)saveSetting
{
    NSMutableDictionary *appSettingDict = [NSMutableDictionary dictionaryWithContentsOfFile:self.plistPath];
    [appSettingDict setValue:self.background forKey:@"background"];
    [appSettingDict setValue:[NSNumber numberWithBool:self.registered] forKey:@"registered"];
    
    BOOL isWrite = [appSettingDict writeToFile:self.plistPath atomically:YES];

    NSLog(@"Save app setting");
    NSLog(@"Background %@", self.background);
    NSLog(@"Write app setting to plist file %d", isWrite);
}


#pragma mark - Plist file

- (NSString *)plistPathInAppWithName:(NSString *)name
{
    NSString* path = [[NSBundle mainBundle] pathForResource:name ofType:nil];
    return path;
}

-(NSString *)plistPathInDocumentWithName:(NSString *)name
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docPath = [paths objectAtIndex:0];
    NSString *path = [docPath stringByAppendingPathComponent:name];
    return path;
}

@end
